package com.ajview.core.config;

import com.ajview.common.core.constant.Constants;
import com.ajview.common.utils.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * PROJECT_NAME: ajview-smile
 *
 * @DESCRIPTION: 国际化设置
 * @DATE 2022-12-21 上午 12:05
 * @Author zhangjunjie
 */
@Configuration
public class LanguageLocalConfig implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        Locale locale = Locale.CHINA;
        String language = request.getHeader(Constants.ACCEPT_LANGUAGE);
        if (StringUtils.isNotBlank(language)) {
            String[] splitLanguage = language.split("_");
            if (splitLanguage.length > 1) {
                locale = new Locale(splitLanguage[0], splitLanguage[1]);
            }
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }

    /**
     * DispatcherServlet 初始化时注入  https://blog.csdn.net/norang/article/details/120390268
     * this.localeResolver = (LocaleResolver)context.getBean("localeResolver", LocaleResolver.class);
     *
     * @return
     */
    @Bean
    public LocaleResolver localeResolver() {
        return new LanguageLocalConfig();
    }
}
